/**
 * 
 */
package com.cnhaimei.vod.net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ArrayBlockingQueue;

import android.R.integer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.cnhaimei.com.PageWrapper;
import com.cnhaimei.com.VODLog;
import com.cnhaimei.net.NetSocket;
import com.cnhaimei.net.TCPSocket;
import com.cnhaimei.net.NetSocket.SocketDataListener;
import com.cnhaimei.vod.bean.Song;
import com.cnhaimei.vod.logic.EventsManager;
import com.cnhaimei.vod.net.dc.CallService;
import com.cnhaimei.vod.net.dc.DCComData;
import com.cnhaimei.vod.net.dc.Player;
import com.cnhaimei.vod.util.Util;

/**
 * @author Administrator
 * 
 */
public class DCManager extends TCPSocket implements SocketDataListener {
	public static final String TAG = "DCManager";
	private static final int MSG_TIME_KEEP = 1;
	private static final int MSG_TIME_OUT = 2;
	private static final int HEART_TIME = 10 * 1000;
	private static final int TIME_OUT = 33 * 1000;
	public static final String ENCODEING = "UTF-8";
	private static final Object lock = new Object();

	public static final int PORT = 2100;	
	
	public static final int PLAYER_STATE_PLAYER = DCComData.COM.EVOD_CTRL_PLAY;
	public static final int PALYER_STATE_PAUSE = DCComData.COM.EVOD_CTRL_PAUSE;
	// pulbic

	/** 操作命令 */
	public static final int DATA_TYPE_COM = 0;
	/** key应答 */
	public static final int DATA_TYPE_KEY_RES = 6;
	/** 心跳 */
	public static final int DATA_TYPE_HEART = 5;
	/** 播放机状态改变 */
	public static final int DATA_TYPE_PSTATE = 1;
	/** 列表数据请求 */
	// public static final int DATA_TYPE_DREQ = 2;
	/** 已选列表数据回复 */
	public static final int DATA_TYPE_SEL = 3;
	/** 已唱列表数据回复 */
	public static final int DATA_TYPE_DONE = 4;

	/** 密码校验 */
	public static final int PASSWORD_CHECK = 0;
	/** 播放 */
	public static final int CTRL_PLAY = 1;
	/** 暂停 */
	public static final int CTRL_PAUSE = 2;
	/** 停止 */
	public static final int CTRL_STOP = 3;
	/** 重唱 */
	public static final int CTRL_REPL = 4;
	/** 下一首 */
	public static final int CTRL_NEXT = 5;
	/** 已选列表加歌 */
	public static final int CTRL_APPEND_SONG = 6;
	/** 已选列表删歌 */
	public static final int CTRL_DELETE_SONG = 7;
	/** 已选列表插播 */
	public static final int CTRL_MOVETO_SONG = 8;
	/** 音量控制 */
	public static final int CTRL_VOICE_VOLUME_SET = 9;
	/** 静音或者取消静 */
	public static final int CTRL_SILENT = 10;
	/** 音轨选择 */
	public static final int CTRL_AUDIO_MUL_CHANNEL_SET = 11;
	/** 麦克风设置 */
	public static final int CTRL_MIC_SET = 12;
	/** 音调设置 */
	public static final int CTRL_TONE_SET = 13;
	/** 气氛设置 */
	public static final int CTRL_MOOD_SET = 14;
	/** 灯光设置 */
	public static final int CTRL_LIGHT_SET = 15;
	/** 音效设置 */
	public static final int CTRL_EFFECT_SET = 16;
	/** 灯光跟随音效 */
	public static final int CTRL_LIGHT_FOLLOW_EFFECT = 17;
	/** 呼叫服务 */
	public static final int CTRL_SERVER = 18;
	/** 音乐重置 */
	public static final int CTRL_RESET = 21;

	public static final int EVOD_PLAY_STATE = 0; /* hplay状态 */
	public static final int EVOD_TRACK_STATE = 1; /* 音轨状态 */
	public static final int EVOD_MIC_VOLUME_STATE = 2; /* 麦克风状态 */
	public static final int EVOD_AUDIO_VOLUME_STATE = 3; /* 音量状态 */
	public static final int EVOD_TONE_VOLUME_STATE = 4; /* 音调状态 */
	public static final int EVOD_MOOD_STATE = 5; /* 气氛状态 */
	public static final int EVOD_LIGHT_STATE = 6; /* 灯光状态 */
	public static final int EVOD_EFFECT_STATE = 7; /* 音效状态 */
	public static final int EVOD_PLAYLIST_STATE = 8; /* 已选列表改变标志 */
	public static final int EVOD_DONELIST_STATE = 9; /* 已唱列表改变标志 */
	public static final int EVOD_SILEND_STATE = 10; /* 静音状态 */
	public static final int EVOD_LIGHT_FOLLOW_EFFECT_STATE = 11; /* 灯光跟随音效状态 */
	public static final int EVOD_TONE_STATE_MIN = 12; /* 音调状态信息 */
	public static final int EVOD_TONE_STATE_MAX = 13; /* 音调状态信息 */
	public static final int EVOD_TONE_STATE_SCALE = 14; /* 音调状态信息 */
	public static final int EVOD_MUSIC_STATE_MIN = 15; /* 音乐状态信息 */
	public static final int EVOD_MUSIC_STATE_MAX = 16; /* 音乐状态信息 */
	public static final int EVOD_MUSIC_STATE_SCALE = 17; /* 音乐状态信息 */
	public static final int EVOD_MIC_STATE_MIN = 18; /* mic状态信息 */
	public static final int EVOD_MIC_STATE_MAX = 19; /* mic状态信息 */
	public static final int EVOD_MIC_STATE_SCALE = 20; /* mic状态信息 */
	public static final int EVOD_CTRL_APPEND_OK	= 23; /*加歌是否成功*/

	/** int类型 */
	public static final int VALUE_TYPE_INT = 0;
	/** 字符串类型 */
	public static final int VALUE_TYPE_STR = 1;
	/** 歌曲信息类型 */
	public static final int VALUE_TYPE_SONG_INFO = 2;

	// public static final int Song_Type_SEL = 1;
	// public static final int Song_Type_SINGED = 2;

	public static final String ENCODING = "UTF-8";
	public static final int Flag = 0x1;
	public static final int HEAD_SIZE = 12;

	// public final byte[] Song_Type_SEL_BYTE = new byte[10];
	// public final byte[] Song_Type_SINGED_BYTE = new byte[10];

	private ByteArrayOutputStream ByteOStream = new ByteArrayOutputStream(1024);

	private byte[] INPUT_BYTE = new byte[4 * 1024];

	// private byte[] szvalue = new byte[92];

	private byte[] writeIntByte = new byte[4];
	private boolean flagAlive;

	HeartKeeper mKeeper;
	ArrayBlockingQueue<PageWrapper> queue = new ArrayBlockingQueue<PageWrapper>(
			100);

	public DCManager() {
		super(PORT, new byte[12]);
		init();
	}

	public DCManager(String ip, int port) {
		super(ip, port, new byte[12]);
		init();
	}

	public void data(NetSocket socket, byte[] head, int headLenth) {
		int flag = readInt(head, 0);
		int dataSize = readInt(head, 4);
		int dataType = readInt(head, 8);
		Log.e(TAG, "flag:" + flag);
		Log.e(TAG, "dataSize:" + dataSize);
		Log.e(TAG, "dataType:" + dataType);
		Log.e(TAG, "headLenth:" + headLenth);
		parseData(socket, flag, dataSize, dataType);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.cnhaimei.net.TCPSocket#onBeforeConnect()
	 */
	@Override
	protected void onBeforeConnect() {
		super.onBeforeConnect();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.cnhaimei.net.TCPSocket#onConnected(boolean)
	 */
	@Override
	protected void onConnected(boolean isSuc) {
		// super.onConnected(isSuc);
		synchronized (lock) {
			queue.clear();
		}
		EventsManager.G().sendEvent(EventsManager.Event.CONNECTING, id, false);
		// autoKeepHeart(); // 取消，需在验证成功后发密码
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.cnhaimei.net.TCPSocket#onDisConnected()
	 */
	@Override
	protected void onDisConnected() {
		Log.e(TAG, "disconnect");
		synchronized (lock) {
			queue.clear();
		}
		mKeeper.removeMessages(MSG_TIME_KEEP);
		EventsManager.G().sendEvent(EventsManager.Event.DISCONNECT, id, false);
	}

	private void parseData(NetSocket socket, int flag, int dataSize,
			int dataType) {
		switch (dataType) {
		case DATA_TYPE_PSTATE: {
			responseState(mInput, dataSize);
		}
			break;
		case DATA_TYPE_SEL: {
			responseSong(mInput, dataSize, EventsManager.Event.SELCT_SONGS);
		}
			break;
		case DATA_TYPE_DONE: {
			responseSong(mInput, dataSize, EventsManager.Event.DONE_SONGS);
		}
			break;
		case DATA_TYPE_KEY_RES: {
			responsePassword(mInput, dataSize);
		}
			break;
		case DATA_TYPE_HEART: {
			responseKeepHeart(mInput, dataSize);
		}
			break;
		case DATA_TYPE_COM: {
			responseCtrl(mInput, dataSize);
		}
			break;
		default:
			break;
		}

	}

	private void init() {
		// byte[] strByte;
		// try {
		// strByte = "playlist".getBytes(ENCODING);
		// System.arraycopy(strByte, 0, Song_Type_SEL_BYTE, 0, strByte.length);
		//
		// strByte = "donelist".getBytes(ENCODING);
		// System.arraycopy(strByte, 0, Song_Type_SINGED_BYTE, 0,
		// strByte.length);
		// } catch (UnsupportedEncodingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

		mKeeper = new HeartKeeper();
		this.setSocketDataListener(this);

	}

	// public void sendData(DCPack pack) {
	//
	// }

	public void starAutoHeart() {
		autoKeepHeart();
		mKeeper.removeMessages(MSG_TIME_OUT);
		mKeeper.sendEmptyMessageDelayed(MSG_TIME_OUT, TIME_OUT);
	}

	private void autoKeepHeart() {
		Log.e(TAG, "keepHeart");
		mKeeper.removeMessages(MSG_TIME_KEEP);
		if (isConneting()) {
			 requestKeep();
			mKeeper.sendEmptyMessageDelayed(MSG_TIME_KEEP, HEART_TIME);
		}
	}

	public void sendOperator(int controlFlag, String str) {
		int iFlag = Flag; // 信息标识，暂定 0x1
		int size = 0; // data大小
		int dataType = DATA_TYPE_COM; // 数据包类型

		int recordCount = 1;
		int com = controlFlag; // 控制命令
		int valueType = VALUE_TYPE_STR; // 控制命令对应数值类型
		// Arrays.fill(szvalue, (byte) 0);
		try {
			byte[] strByte = str.getBytes(ENCODING);
			// System.arraycopy(strByte, 0, szvalue, 0, strByte.length);
			size = 12 + strByte.length;

			final ByteArrayOutputStream byteOut = ByteOStream;
			byteOut.reset();
			writejHead(byteOut, iFlag, size, dataType);
			writeInt(byteOut, recordCount);
			writeInt(byteOut, com);
			writeInt(byteOut, valueType);
			byteOut.write(strByte);

			byteOut.writeTo(mOutput);

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendOperator(int controlFlag, int value) {
		sendOperator(controlFlag, value, 0);
	}

	public void sendOperator(int controlFlag, int value1, int value2) {
		int iFlag = Flag; // 信息标识，暂定 0x1
		int size = 0; // data大小
		int dataType = DATA_TYPE_COM; // 数据包类型

		int recordCount = 1;

		int com = controlFlag; // 控制命令
		int valueType = VALUE_TYPE_INT; // 控制命令对应数值类型
		try {
			size = 20;
			final ByteArrayOutputStream byteOut = ByteOStream;
			byteOut.reset();
			writejHead(byteOut, iFlag, size, dataType);
			writeInt(byteOut, recordCount);
			writeInt(byteOut, com);
			writeInt(byteOut, valueType);
			writeInt(byteOut, value1);
			writeInt(byteOut, value2);

			byteOut.writeTo(mOutput);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
		
	public void insertSong(Song song) {
		int iFlag = Flag; // 信息标识，暂定 0x1
		int size = 0; // data大小
		int dataType = DATA_TYPE_COM; // 数据包类型

		int recordCount = 1;

		int com = CTRL_APPEND_SONG; // 控制命令
		int valueType = VALUE_TYPE_SONG_INFO; // 控制命令对应数值类型
		try {
			size = 92;
			final ByteArrayOutputStream byteOut = ByteOStream;
			byteOut.reset();
			writejHead(byteOut, iFlag, size, dataType);
			writeInt(byteOut, recordCount);
			writeInt(byteOut, com);
			writeInt(byteOut, valueType);

			byte num[] = new byte[8];
			copyString(song.getNumb(), num);
			byte lang[] = new byte[4];
			copyString(song.getLang(), lang);
			byte flag[] = new byte[4];
			byte name[] = new byte[32];
			copyString(song.getName(), name);// 歌曲名称
			byte star[] = new byte[24];
			copyString(song.getSinger(), star);// 歌手名称

			byteOut.write(num);
			byteOut.write(lang);
			byteOut.write(flag);
			byteOut.write(name);
			byteOut.write(star);
			byteOut.write(song.getaEff());// 音频效果索引
			byteOut.write(song.getvEff());// 视频效果索引
			byteOut.write(song.getVolm());// 音乐音量基准
			byteOut.write(song.getVolv_base());// 人声音量基准
			byteOut.write(song.getTrck());// 音轨控制模式
			byteOut.write(0);// 用户控制预留
			byteOut.write(0);// 文件的模式
			byteOut.write(0);// 播放的模式

			byteOut.writeTo(mOutput);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param song
	 * @param numb
	 * @throws UnsupportedEncodingException
	 */
	private void copyString(String s, byte[] numb)
			throws UnsupportedEncodingException {
		if (s == null) {
			return;
		}
		byte[] numbb = s.getBytes(ENCODING);// 歌曲编号
		System.arraycopy(numbb, 0, numb, 0, numbb.length);
	}

	public void requestSelSong(int start, int count) {
		requestSong(DATA_TYPE_SEL, start, start + count - 1);
	}

	public void requestSingedSong(int start, int count) {
		requestSong(DATA_TYPE_DONE, start, start + count - 1);
	}

	private void requestSong(int songType, int start, int end) {
		int iFlag = Flag; // 信息标识，暂定 0x1
		int size = 0; // data大小
		int dataType = songType; // 数据包类型

		int recordCount = 1;
		// byte[] songTypeByte = null; // 列表名

		// if (songType == Song_Type_SEL) {
		// songTypeByte = Song_Type_SEL_BYTE;
		// } else {
		// songTypeByte = Song_Type_SINGED_BYTE;
		// }

		try {

			synchronized (lock) {
				size = 12;// + songTypeByte.length;
				final ByteArrayOutputStream byteOut = ByteOStream;
				byteOut.reset();
				writejHead(byteOut, iFlag, size, dataType);
				writeInt(byteOut, recordCount);
				writeInt(byteOut, start);
				writeInt(byteOut, end);
				// byteOut.write(songTypeByte);

				byteOut.writeTo(mOutput);
				PageWrapper p = new PageWrapper();
				p.setCurPage(start);
				Log.e("TAG", "pw curPage request:" + p.getCurPage());

				queue.add(p);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void requestKeep() {
		int iFlag = Flag; // 信息标识，暂定 0x1
		int size = 0; // data大小
		int dataType = DATA_TYPE_HEART; // 数据包类型

		int recordCount = 1;
		int life = 1;

		try {
			size = 8;
			final ByteArrayOutputStream byteOut = ByteOStream;
			byteOut.reset();
			writejHead(byteOut, iFlag, size, dataType);
			writeInt(byteOut, recordCount);
			writeInt(byteOut, life);

			byteOut.writeTo(mOutput);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void responsePassword(InputStream in, int dataSize) {

		boolean isSuc = false;
		String rtn = null;
		Arrays.fill(INPUT_BYTE, (byte) 0);

		try {

			mInput.read(INPUT_BYTE, 0, dataSize);
			rtn = Util.readString(INPUT_BYTE, 4, ENCODEING);
			Log.e("TAG", "rekey:" + rtn);
			if ("ok".equalsIgnoreCase(rtn)) {
				isSuc = true;
			}
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		}
		EventsManager.G().sendEvent(EventsManager.Event.CHCKD_PAS, rtn, isSuc);
	}

	private void responseCtrl(InputStream in, int dataSize) {
		Log.e(TAG, "responseCtrl");
		
		boolean isSuc = false;
		String rtn = null;
		Arrays.fill(INPUT_BYTE, (byte) 0);
		
		boolean bFirstService = true;

		try {
			mInput.read(INPUT_BYTE, 0, dataSize);
			ByteArrayInputStream bin = new ByteArrayInputStream(INPUT_BYTE);
			int recordCount = Util.readInt(bin);
			int index = 4;

			for (int i = 0; i < recordCount; i++) {
				int com = Util.readInt(bin);
				index += 4;
				int byteType = 0;
				switch (com) {
				case CTRL_SERVER: /* 服务 */
					if (bFirstService) {
						bFirstService = false;
						CallService.G().clearItems();
					}
					byteType = Util.readInt(bin);//字节类型：int，str，song
					index += 4;
					if (VALUE_TYPE_STR == byteType) {
						rtn = Util.readString(INPUT_BYTE, index, ENCODEING);
						int tmpIdx = rtn.indexOf(';');
						if (tmpIdx > -1) {
							rtn = rtn.substring(0, tmpIdx);
						}
						CallService.G().addItems(rtn.split(","));
					}
					break;
				case EVOD_CTRL_APPEND_OK: /* 加歌是否成功 */
					byteType = Util.readInt(bin);//字节类型：int，str，song
					index += 4;
					if (VALUE_TYPE_STR == byteType) {
						rtn = Util.readString(INPUT_BYTE, index, ENCODEING);
						
						EventsManager.G().sendEvent(EventsManager.Event.SELECT_SONG_RESULT, rtn, isSuc);
					}
					break;
				default:
					break;
				}
			}
			isSuc = true;
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		}
	}
	
	private void responseState(InputStream in, int dataSize) {
		Log.e(TAG, "responseState");

		boolean isSuc = false;
		Arrays.fill(INPUT_BYTE, (byte) 0);
		boolean hasSel = false;
		boolean hasDon = false;

		try {
			mInput.read(INPUT_BYTE, 0, dataSize);
			ByteArrayInputStream bin = new ByteArrayInputStream(INPUT_BYTE);
			int recordCount = Util.readInt(bin);

			for (int i = 0; i < recordCount; i++) {
				int com = Util.readInt(bin);
				int value = Util.readInt(bin);
//				Log.e(TAG, String.valueOf(com) + ":" + String.valueOf(value));
				if (Util.VLOG) {
					VODLog.e(TAG, String.valueOf(com) + ":"
							+ String.valueOf(value));
				}
				switch (com) {
				case EVOD_PLAY_STATE: /* hplay状态 */
					Player.G().setPlayerState(value);
					break;
				case EVOD_TRACK_STATE:/* 音轨状态 */
					Player.G().setTrackState(value);
					break;
				case EVOD_MIC_VOLUME_STATE:/* 麦克风状态 */
					Player.G().setMicVolume(value);
					break;
				case EVOD_AUDIO_VOLUME_STATE:/* 音量状态 */
					Player.G().setAudioVolume(value);
					break;
				case EVOD_TONE_VOLUME_STATE:/* 音调状态 */
					Player.G().setToneVolume(value);
					break;
				case EVOD_MOOD_STATE:/* 气氛状态 */
					Player.G().setMood(value);
					break;
				case EVOD_LIGHT_STATE:/* 灯光状态 */
					Player.G().setLightState(value);
					break;
				case EVOD_EFFECT_STATE:/* 音效状态 */
					Player.G().setEffectState(value);
					break;
				case EVOD_PLAYLIST_STATE:/* 已选列表改变标志 */
					Player.G().setPlaylistState(value);
					hasSel = true;
					break;
				case EVOD_DONELIST_STATE:/* 已唱列表改变标志 */
					Player.G().setDonelistState(value);
					hasDon = true;
					break;
				case EVOD_SILEND_STATE:/* 静音状态 */
					Player.G().setSlient(value);
					break;
				case EVOD_LIGHT_FOLLOW_EFFECT_STATE:/* 灯光跟随音效状态 */
					Player.G().setLightFollowEffect(value);
					break;
				case EVOD_TONE_STATE_MIN: /* 音调状态信息 */
					Player.G().setToneMin(value);
					break;
				case EVOD_TONE_STATE_MAX: /* 音调状态信息 */
					Player.G().setToneMax(value);
					break;
				case EVOD_TONE_STATE_SCALE: /* 音调状态信息 */
					Player.G().setToneScale(value);
					break;
				case EVOD_MUSIC_STATE_MIN: /* 音乐状态信息 */
					Player.G().setAudioMin(value);
					break;
				case EVOD_MUSIC_STATE_MAX: /* 音乐状态信息 */
					Player.G().setAudioMax(value);
					break;
				case EVOD_MUSIC_STATE_SCALE: /* 音乐状态信息 */
					Player.G().setAudioScale(value);
					break;
				case EVOD_MIC_STATE_MIN: /* mic状态信息 */
					Player.G().setMicMin(value);
					break;
				case EVOD_MIC_STATE_MAX: /* mic状态信息 */
					Player.G().setMicMax(value);
					break;
				case EVOD_MIC_STATE_SCALE: /* mic状态信息 */
					Player.G().setMicScale(value);
					break;
				default:
					break;
				}
			}
			isSuc = true;

		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		}

		EventsManager.G().sendEvent(EventsManager.Event.PLYER_STATE, null,
				isSuc);

		if (hasSel) {
			EventsManager.G().sendEvent(EventsManager.Event.SELCT_CHANG, null,
					isSuc);
		}

		if (hasDon) {
			EventsManager.G().sendEvent(EventsManager.Event.DONE_CHANG, null,
					isSuc);
		}
	}

	private void responseSong(InputStream in, int dataSize, int event) {
		Log.e(TAG, "responseSong");

		boolean isSuc = false;
		Arrays.fill(INPUT_BYTE, (byte) 0);
		ArrayList<Song> lst = new ArrayList<Song>(10);
		PageWrapper pw = null;

		synchronized (lock) {
			try {

				Log.e(TAG, "dataSize:" + dataSize);
				mInput.read(INPUT_BYTE, 0, dataSize);
				int recordCount = readInt(INPUT_BYTE, 0);
				Log.e(TAG, "ret count:" + recordCount);
				int index = 4;
				for (int i = 0; i < recordCount; i++) {
					Song s = new Song();
					String num = Util.readString(INPUT_BYTE, index, ENCODING);
					index += 8;
					String lang = Util.readString(INPUT_BYTE, index, ENCODING);
					index += 4;
					index += 4;
					String name = Util.readString(INPUT_BYTE, index, ENCODEING);
					index += 32;
					String star = Util.readString(INPUT_BYTE, index, ENCODING);
					index += 24;
					byte aEff = INPUT_BYTE[index];
					++index;
					byte vEff = INPUT_BYTE[index];
					++index;
					byte volm = INPUT_BYTE[index];
					++index;
					byte volv = INPUT_BYTE[index];
					++index;
					byte track = INPUT_BYTE[index];
					++index;
					// unsigned char user_ctrl;
					++index;
					// unsigned char file_mode;
					++index;
					// unsigned char play_mode
					++index;

					s.setName(name);
					s.setSinger(star);
					if (star != null) {
						s.setSingerName(star.replace("|", " "));
					}
					s.setNumb(num);
					s.setLang(lang);
					s.setaEff(aEff);
					s.setvEff(vEff);
					s.setVolm(volm);
					s.setVolv_base(volv);
					s.setTrck(track);
					lst.add(s);
					// s.setDefinition(vType);
					// Log.e(TAG, "vType:" + vType);
					Log.e(TAG, "num:" + num);
					Log.e(TAG, "lang:" + lang);
					Log.e(TAG, "name:" + name);
					Log.e(TAG, "star:" + star);
					Log.e(TAG, "aEff:" + aEff);
					Log.e(TAG, "vEff:" + vEff);
					Log.e(TAG, "volm:" + volm);
					Log.e(TAG, "volv:" + volv);
					Log.e(TAG, "track:" + track);
					Log.e(TAG, "index:" + index);
				}
				isSuc = true;

			} catch (Exception e) {
				// TODO
				e.printStackTrace();
			}

			pw = queue.poll();
			if (pw == null) {
				Log.e(TAG, "pw is null");
				pw = new PageWrapper();
			} else {
				Log.e(TAG, "pw curPage response:" + pw.getCurPage());
			}

			pw.setData(lst);
		}

		EventsManager.G().sendEvent(event, pw, isSuc);
	}

	private void responseKeepHeart(InputStream mInput, int dataSize) {
		String rtn = null;
		Arrays.fill(INPUT_BYTE, (byte) 0);

		try {

			mInput.read(INPUT_BYTE, 0, dataSize);
			flagAlive = true;
			VODLog.e(TAG, "keepHeart: response");
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		}

	}

	public void writeInt(OutputStream os, int v) throws IOException {
		writeIntByte[0] = (byte) (v & 0xff);
		writeIntByte[1] = (byte) ((v >> 8) & 0xff);
		writeIntByte[2] = (byte) ((v >> 16) & 0xff);
		writeIntByte[3] = (byte) ((v >> 24) & 0xff);
		os.write(writeIntByte);
	}

	private void writejHead(OutputStream os, int iFlag, int size, int dataType)
			throws IOException {
		writeInt(os, iFlag);
		writeInt(os, size);
		writeInt(os, dataType);
	}

	private int readInt(byte[] b, int start) {
		int rtn = b[start + 3] & 0xff;
		rtn = (rtn << 8) + (b[start + 2] & 0xff);
		rtn = (rtn << 8) + (b[start + 1] & 0xff);
		rtn = (rtn << 8) + (b[start + 0] & 0xff);
		return rtn;
	}

	private class HeartKeeper extends Handler {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_TIME_KEEP:
				VODLog.e(TAG, "keepHeart: send");
				 autoKeepHeart();
				Log.e(TAG, "keep");
//				requestKeep();

				break;
			case MSG_TIME_OUT:
				if (flagAlive) {
					flagAlive = false;
					mKeeper.sendEmptyMessageDelayed(MSG_TIME_OUT, TIME_OUT);
				} else {
					VODLog.e(TAG, "keepHeart: time out");
					close();
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}

	public void start() {
		if (!isRun()) {
			new Thread(this).start();
		}

	}

	public void stop() {
		// TODO Auto-generated method stub

	}

}
